package client;

/*Copyright 2010 Dietmar Wieser, Margit Mutschlechner and Florian Häser. All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this list of
 conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice, this list
 of conditions and the following disclaimer in the documentation and/or other materials
 provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY Dietmar Wieser, Margit Mutschlechner and Florian Häser ``AS IS''
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 Dietmar Wieser, Margit Mutschlechner and Florian Häser OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 The views and conclusions contained in the software and documentation are those of the
 authors and should not be interpreted as representing official policies, either expressed
 or implied, of Dietmar Wieser, Margit Mutschlechner and Florian Häser.
 */
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import client.gui.GUIController;
import client.logic.BlueToothConnector;
import client.logic.clientmodel.ClientAuthorResponse;
import client.logic.clientmodel.ClientLoginResponse;
import client.logic.clientmodel.ClientProfile;
import client.logic.connect.ServerConnector;
import client.persistence.PersistenceController;

/**
 * The Controller class handles the access to the logic layer of the
 * source-code.
 * 
 * @author Dietmar Wieser
 */
public class Controller implements ControllerInterface {
	/** The instance of the Controller */
	private static Controller INSTANCE = null;
	/** The current User-profile */
	private ClientProfile actualProfile;
	/** The instance of the main activity */
	private DBLPClient client;
	/** The suggested Authors, generated by the server */
	private ClientAuthorResponse actualAuthors = null;

	/** constructor */
	public Controller(DBLPClient c) {
		this.client = c;
		GUIController.initGUIController();
		PersistenceController.initPersistenceController();
	}

	/**
	 * Initializes the Controller instance.
	 * 
	 * @param c
	 *            the instance of the main activity class.
	 */
	public static void initController(DBLPClient c) {
//		if (INSTANCE == null) {
			INSTANCE = new Controller(c);
//		}
	}

	/**
	 * Returns the instance of the Controller.
	 * 
	 * @return the instance of the Controller
	 */
	public static Controller getInstance() {
		return INSTANCE;
	}

	/** To finish the main activity */
	public void exit() {
//		INSTANCE=null;
		Log.i("","Controller.exit");
		client.finish();
	}

	/**
	 * To start the Application. This class requests the whole active
	 * conferences from the server and gets the stored username.
	 */
	public void startApplication() {
		GUIController.getInstance().showProgressDialog(client, "Connecting to Server...",
				"Requesting current conferences.");
		String[] conferences = ServerConnector.requestConferences();
		String[] name = PersistenceController.getInstance().readAuthorName();
		String firstName = "";
		String lastName = "";
		if ((name != null) && (name.length > 1)) {
			firstName = name[0];
			lastName = name[1];
		}
		GUIController.getInstance().dismissProgressDialog();
		GUIController.getInstance().showLoginForm(conferences, firstName,
				lastName);
	}
	

	/**
	 * Sets the current user-profile.
	 * 
	 * @param firstName
	 *            firstname of the user.
	 * @param lastName
	 *            lastname of the user.
	 * @param conf
	 *            the selected conference.
	 * @param authorId
	 *            the database-id of the current user.
	 * */
	public void setActualClientProfile(String firstName, String lastName,
			String conf, long authorId) {
		String mac = BlueToothConnector.getMacAddress();
		System.out.println("--> actual ClientProfile -> firstName: "
				+ firstName + ", lastName: " + lastName + ", conference: "
				+ conf + " mac: " + mac + " authorId: " + authorId);
		this.actualProfile = new ClientProfile(firstName, lastName, mac, conf,
				authorId);
	}

	/**
	 * Requests adequate authors from the server.
	 * 
	 * @return a list of authors with their attributes
	 * */
	public ClientAuthorResponse requestAuthors() {
		actualAuthors = ServerConnector.requestSuggestedAuthors(actualProfile);
		return actualAuthors;
	}

	/**
	 * Stores the name of the current user.
	 * 
	 * @param firstName
	 *            the firstname of the user.
	 * @param lastName
	 *            the lastname of the user.
	 * */
	public void storeAuthorName(String firstName, String lastName) {
		PersistenceController.getInstance()
				.storeAuthorName(firstName, lastName);
	}

	/** Scans the bluetooth range to discover adequate authors. */
	public void discoverDevices() {
		client.startService(new Intent(client.getContext(),client.logic.BlueToothConnector.class));
//		client.startActivity(new Intent(client.getContext(),
//				client.logic.BlueToothConnector.class));
	}

	/**
	 * This method is called if the bluetooth discovery has finished
	 * 
	 * @param successful
	 *            true if there was no error, false otherwise
	 * */
	public void discoveryFinished(boolean successful) {
		client.stopService(new Intent(client.getContext(),client.logic.BlueToothConnector.class));
		ClientAuthorResponse nearAuthors = null;
		nearAuthors = BlueToothConnector.getNearClients(actualAuthors);
		GUIController.getInstance().dismissProgressDialog();
		GUIController.getInstance().showAuthorList(nearAuthors, true);
	}

	public ClientAuthorResponse getClientAuthorResponse() {
		return this.actualAuthors;
	}

	/**
	 * Requests all publications for a special author.
	 * 
	 * @return a list of all publications reguarding the selected author.
	 * @param author
	 *            the name of the author.
	 * */
	public String[] requestPublications(String author) {
		return ServerConnector.requestPublications(author);
	}

	/**
	 * This method validates the user profile by requesting the server.
	 * 
	 * @param firstName
	 *            the firstname of the current user.
	 * @param lastName
	 *            the lastname of the current user.
	 * @param conference
	 *            the selected conference.
	 * */
	public void requestLogin(String firstName, String lastName,
			String conference) {
		ClientLoginResponse clr = ServerConnector.requestLogin(firstName,
				lastName);
		if (clr != null) {
			if (clr.getFirstNameSize() == 1) {
				this.setActualClientProfile(clr.getFirstNameAt(0), clr
						.getLastName(), conference, clr.getAuthorIdsAt(0));
				this.storeAuthorName(clr.getFirstNameAt(0), clr.getLastName());
				GUIController.getInstance().showMainForm();
			} else if (clr.getFirstNameSize() > 1) {
				GUIController.getInstance().showLoginForm2(conference, clr);
			} else {
				GUIController.getInstance().showToast("Sorry, couldn't find your name");
				GUIController.getInstance().showLoginForm(
						new String[] { conference }, firstName, lastName);
			}
		} else {
			GUIController.getInstance().showToast("Sorry, couldn't find your name");
			GUIController.getInstance().showLoginForm(
					new String[] { conference }, firstName, lastName);
		}
	}

	/**
	 * Returns the shared preference file of the application
	 * 
	 * @return shared preference
	 */

	public SharedPreferences getSharedPreferences() {
		return client.getSharedPreferences("DBLPPersistence", 0);
	}

	/**
	 * Returns the context of the main activity so that other classes can start
	 * activities in this context.
	 * 
	 * @return context of the main activity
	 */
	public Context getContext() {
		return client.getContext();
	}
}
